# -*- coding: utf-8 -*-

import logging

from model import business_lock_api as db_business_lock
LOG = logging.getLogger()


class DBUniqueLock(object):
    def __init__(self, param_prefix, value, description, timeout):
        self.param_prefix = param_prefix                   # string 锁的前缀
        self.value = str(value)                            # string 锁的具体内容
        self.param = self.param_prefix + '-' + self.value  # string 对应DB中真正的unique key
        self.description = description                     # string 描述性信息
        self.timeout = timeout
        self.lock_auto_id = None

    def __enter__(self):
        self.acquire()
        LOG.info('model unique lock enter success')

    def __exit__(self, exc_type, exc_value, traceback):
        LOG.info('exe_type: %s' % exc_type)
        LOG.info('exc_value: %s' % exc_value)
        LOG.info('traceback: %s' % traceback)
        self.release()
        LOG.info('model unique lock exit success')

    def acquire(self):
        lock_data = {
            'param': self.param,
            'description': self.description,
            'timeout': self.timeout,
        }
        # 加锁。如果加锁失败，则直接异常退出
        self.lock_auto_id = db_business_lock.get_business_lock(**lock_data)
        LOG.info('acquire model unique lock success param %s description %s' % (self.param, self.description))

    def release(self):
        LOG.info('release model unique lock_auto_id %d param %s description %s' %
                 (self.lock_auto_id, self.param, self.description))
        if self.lock_auto_id:
            db_business_lock.delete_lock_by_auto_id(auto_id=self.lock_auto_id)
            LOG.info('release model unique lock success')
